package diet

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"io"
	"net/http"
)

func (b Base) Nutrition(c *gin.Context, req *NutritionRequest) *NutritionResponse {
	diet := model.Diet{}
	diet.ID = req.DietId
	err := diet.Get(config.DB)
	if err != nil {
		handler.Errorf(c, "diet 不存在")
		return nil
	}

	foodReq := []FoodReq{}

	for i := range req.Foods {
		//file.DeleteFile(req.Foods[i].Region)
		foodReq = append(foodReq, FoodReq{
			Num:  req.Foods[i].Food,
			Name: req.Foods[i].Name,
		})
	}

	sid := model.Sid(diet.Foods.MaskSid)
	reqBody := DepthBackRequestBody{
		ImageId: diet.PicId.String(),
		MaskId:  sid.String(),
		Foods:   foodReq,
	}
	bodyBytes, _ := json.Marshal(reqBody)

	// 请求 python
	url := fmt.Sprintf(viper.GetString("depthback"))
	log.Info(url)
	request, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		log.Error("resp error is ", resp)
		handler.Errorf(c, "failed to lap depth")
		return nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	rsp := DepthBackResp{}
	err = json.Unmarshal(body, &rsp)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	diet.Foods.FoodList = rsp.Results
	_ = diet.Save(config.DB)
	//_ = file.DeleteFile(sid)

	return &NutritionResponse{
		DepthBackResp: rsp,
	}
}

type NutritionRequest struct {
	DietId uint `json:"dietId"`
	Foods  []struct {
		Food   int       `json:"food"`
		Region model.Sid `json:"region"`
		Name   string    `json:"name"`
	} `json:"foods"`
}

type NutritionResponse struct {
	DepthBackResp
}

type FoodReq struct {
	Num  int    `json:"num"`
	Name string `json:"name"`
}

type DepthBackRequestBody struct {
	ImageId string    `json:"imageId"`
	MaskId  string    `json:"maskId"`
	Foods   []FoodReq `json:"foods"`
}

type DepthBackResp struct {
	Results []model.Food `json:"results"`
}
